`
https://leetcode.cn/problems/magnetic-force-between-two-balls/
`

/**
 * @param {number[]} position
 * @param {number} m
 * @return {number}
 */
var maxDistance = function (position, m) {
  // 同 LC 2517. 礼盒的最大甜蜜度
  const n = position.length
  position.sort((a, b) => a - b)

  // 给定 d，能否选出 m 个球，使得任意两球之间的磁力 >= d
  const check = (d) => {
    let count = 1
    let last = position[0]
    for (let i = 1; i < n; i++) {
      if (Math.abs(position[i] - last) >= d) {
        last = position[i]
        count++
        if (count >= m) return true
      }
    }
    return false
  }

  let left = 0, right = position.at(-1) - position[0] + 1
  while (left + 1 < right) {
    const mid = left + Math.floor((right - left) / 2)
    if (check(mid)) {
      left = mid
    } else {
      right = mid
    }
  }
  return left
};